<?php
/**
 * Created by PhpStorm.
 * User: trnall
 * Date: 2020/10/16
 * Time: 11:21
 */

namespace app\sapi\controller\v1;

use app\common\controller\Api;
use app\api\service\ArticleService;
use app\common\model\GoodsSpellGroup;
use app\common\model\GoodsToday;
use app\common\model\LogMoneys;
use app\common\model\ManystoreConfig;
use app\common\model\Order;
use think\Config;
use app\api\service\UserService;
use wechat\Wechat;
use think\Db;
use think\Validate;
use app\common\model\Article as ArticleModel;
use app\common\library\Sms as Smslib;

/**
 * 首页
 * Class Index
 * @package app\sapi\controller\v1
 */
class Index extends Api
{
    protected $noNeedLogin = ['upload','gzharticle','jssdk','cancellation','init','articleInfo'];
    protected $noNeedRight = ['*'];

    /**
     * 首页数据统计
     */
    public function index()
    {
        $shopId = SHOP_ID;
        $orderModel = new Order();
        $logMoneyModel = new LogMoneys();
        //今日支付总金额
        $todayOrderMoney = $logMoneyModel->getTotalMoney(['shop_id' => $shopId, 'money_type' => 1, 'log_time' => ['>', strtotime(date("Y-m-d", time()))]]);
        //昨日支付总金额
        $yesterdayOrderMoney = $logMoneyModel->getTotalMoney(['shop_id' => $shopId, 'money_type' => 1, 'log_time' => ['between', [strtotime(date("Y-m-d", time() - 86400)), strtotime(date("Y-m-d", time()))]]]);
        //总支付金额
        $totalOrderMoney = $logMoneyModel->getTotalMoney(['shop_id' => $shopId, 'money_type' => 1]);
        //未处理订单数
        $noHandleOrder = $orderModel->getNoHandleNum(['shop_id' => $shopId]);

        $shopConfig = (new ManystoreConfig())->manystore_config();
        $earlyWarningNum = $shopConfig['early_warning'] ?? Config::get('shop.early_warning');//库存预警数量
        $goodsIds = (new \app\common\model\Goods())->where(['shop_id' => $shopId])->column('id');
        //库存预警（库存低于5时预警）
        $todayNum = (new GoodsToday())
            ->where([
                'status' => 1,
                'goods_id' => ['in', $goodsIds],
                'stock_num' => ['<=', $earlyWarningNum]
            ])
            ->count();
        $spellGroupNum = (new GoodsSpellGroup())
            ->where([
                'status' => 1,
                'goods_id' => ['in', $goodsIds],
                'stock_num' => ['<=', $earlyWarningNum]
            ])
            ->count();
        $earlyWarningTotalNum = $todayNum + $spellGroupNum;

        $data = [
            'today_order_money' => $todayOrderMoney,
            'yesterday_order_money' => $yesterdayOrderMoney,
            'total_order_money' => $totalOrderMoney,
            'no_handle_order' => $noHandleOrder,
            'early_warning_total_num' => $earlyWarningTotalNum
        ];
        $this->success('数据统计', $data, 200);
    }

    /**
     * 上传图片到oss
     */
    public function upload()
    {
        $pdir = 'front/'.date('Ymd').'/';
        if(!isset($_FILES['file']) || !$_FILES['file'] || $_FILES['file']['error']){
            $this->error('上传出错');
        }
        if ($_FILES['file']['size']>10485760) {
            $this->error('上传文件过大');
        }
        $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        if(!in_array($extension,['jpg','jpeg','png','gif','mp4'])){
            $this->error('上传格式不允许');
        }
        $file = file_get_contents($_FILES['file']["tmp_name"]);
        $ossService = new \services\OssService();
        /*@todo img*/
        $filename = md5($_FILES['file']['name'].date('YmdHi').rand(1000,9999)).'.'.$extension;
        $upload_file=$ossService->upload_file_content($file,$pdir.$filename);
        if ($upload_file) {
            $this->success('上传成功', ['url' => '/' . $pdir.$filename]);
        } else {
            $this->error('上传出错');
        }
    }

    public function richtext(ArticleService $articleService)
    {
        $id = input('id/d', 1);
        $res = $articleService->getArticleList($id, 1, 1);
        if ($res['total'] <= 0) $this->error('内容不存在');
        $this->success('', $res['data'][0]);
    }

    public function download()
    {
        $this->success('abc');
    }

    // 关注公众号文章
    public function gzharticle()
    {
        $this->success('',config('gzharticle'));
    }


    public function qywx()
    {
        $this->success('',config('qywx'));
    }


    public function desc()
    {
        $data = [
            ['id' => '用户退单','name'=>'用户退单'],
            ['id' => '找不到订单','name'=>'找不到订单'],
            ['id' => '多平台提交','name'=>'多平台提交'],
            ['id' => '其他','name'=>'其他'],
        ];
        $this->success('',$data);
    }

    public function init()
    {
        // 客服微信
        $data['kfwx'] = '15172028580';
        $data['qywx'] = config('qywx');
        $data['gzharticle'] = config('gzharticle');
        $data['zhqe'] = ['title'=>'助力外卖商家精准营销服务','image'=>'https://oss.chbcplus.com/img/WechatIMG4762.png'];
        $count = Db::name('user')->where('user_type',1)->count();
        $data['num'] = $count+8680;
        $this->success('',$data);
    }

    /**
     * 微信群
     * @DateTime 2023-04-20T22:58:22+0800
     * @param    UserService              $userService [description]
     * @return   [type]                                [description]
     */
    public function wechatgroup(UserService $userService)
    {
        $lat = $this->lat;
        $lng = $this->lng;
        if (!$lat || !$lng) $this->error('未能正确获取到您的位置');
        $data = $userService->getLocationWxGroup($lat, $lng,1);
        if (empty($data)) $this->error('附近暂无群', null);
        foreach ($data as $key => $value) {
            $data[$key]['qrcode_image'] = config('upload_domain').$value['qrcode_image'];
        }
        $this->success('', $data);
    }

    public function jssdk()
    {
        $url = urldecode(input('uri', ''));
        $config = Config::get('jmgzh');
        $wecaht = new Wechat($config['appid'], $config['appsecret']);
        $data = $wecaht->creatSign($url);
        $data['debug'] = Config::get('app_debug');
        $data['debug'] = false;
        $data['jsApiList'] = [
            'checkJsApi', //判断当前客户端版本是否支持指定JS接口
//            'onMenuShareAppMessage', //分享接口
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'getLocation', //获取位置
            'openLocation', //打开位置
            /*'scanQRCode', //扫一扫接口
            'chooseWXPay', //微信支付
            'chooseImage', //拍照或从手机相册中选图接口
            'previewImage', //预览图片接口
            'uploadImage' //上传图片*/
        ];
        $data['openTagList'] = ['wx-open-launch-weapp'];
        $this->success('', $data);
    }

    /**
     * 注销
     * @DateTime 2023-05-05T21:09:58+0800
     * @param    string                   $value [description]
     * @return   [type]                          [description]
     */
    public function cancellation()
    {
        $user = UserModel::get($this->auth->id);
        if (!$user) {
            $this->error('注销失败');
        }
        $user->status = 'cancel';
        $user->updatetime = time();
        $user->save();
        $this->success('注销成功');
    }


    public function wechatInfo()
    {
        $appid = Config::get('wx_gzh.appid');
        $appSecret = Config::get('wx_gzh.appsecret');
        $openid = '';
        $unionid = \app\common\model\User::where('id',$this->auth->id)->value('unionid');
        if ($unionid) {
            $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'h5'])->value('openid');
        }
        if (!$openid) {
            $this->success('没有关注',['status'=>0]);
        }
        $wechat = new Wechat($appid,$appSecret);
        $info = $wechat->getBaseInfo($openid);
        if (!isset($info['subscribe']) || !$info['subscribe']) {
            $this->success('没有关注',['status'=>0]);
        }
        $gzxx = $info['subscribe'];
        if ($gzxx==1) {
            $this->success('已关注',['status'=>1]);
        } else {
            $this->success('没有关注',['status'=>0]);
        }
    }


    public function articleInfo()
    {
        $id = input('id/d',0);
        $ArticleModel = new ArticleModel();
        $list = $ArticleModel->where(['status'=>'normal','type'=>4,'id'=>$id])->find();
        $this->success('',$list);
    }

    public function bindMobile()
    {
        $user = $this->auth->getUser();
        if ($user['mobile']) {
            $this->error('用户已绑定手机号');
        }
        $mobile = $this->request->post('mobile');
        $shop_no = $this->request->post('shop_no');
        $captcha = $this->request->post('code');
        if (!$mobile || !$captcha) {
            $this->error('请把信息补充完整');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号格式错误');
        }
        if (!$shop_no) $this->error('请先绑定店铺');
        $shop = Db::name('shop')->where('shop_no='.$shop_no)->find();
        if (!$shop) $this->error('请先绑定店铺手机号');
        if ($shop['phone']!=$mobile) $this->error('该手机号不能绑定当前店铺');
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->where('user_type',1)->find()) {
            $this->error('手机号已被占用');
        }
        $result = Smslib::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error('验证码不正确');
        }
        Db::startTrans();
        try {
            $verification = $user->verification;
            $verification->mobile = 1;
            $user->verification = $verification;
            $user->mobile = $mobile;
            // 查找有没有这个手机号的资金流水，如果有流水需要把余额加上
            $user_money_log = Db::name('user_money_log')->where(['phone'=>$mobile,'log_status'=>0])->order('id desc')->find();
            if ($user_money_log) {
                $user->money = $user_money_log['after_money'];
            }
            $user->save();
            Db::name('user_money_log')->where('phone',$mobile)->update([
                'log_status' => 1,
                'user_id' => $user->id,
                'update_dt' => date('Y-m-d H:i:s'),
            ]);
            Smslib::flush($mobile, 'changemobile');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('数据库操作失败');
        }

        $this->success('手机号绑定成功');
    }
}